package ventanasYDialogos;

import entidades.Jugador;
import gestion.comunicacion.Cliente;
import gestion.comunicacion.ClienteVirtual;
import gestion.comunicacion.Servidor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import jugadorVirtual.ElegirColor;

public class VElegirColor extends javax.swing.JFrame {

    private String usuario;
    private String ipServer;
    private Cliente cli;
    private Servidor ser;
    private ArrayList<JRadioButton> arrayJRB;
    private int contElegidos = 0;
    private int tiempoTurno = 250;
    private int tipoMision = 0;

    //Constructor del servidor
    public VElegirColor(String usuario, Servidor ser) {
        initComponents();
        initPropio();
        this.ser = ser;
        this.jB_iniciarPartida.setEnabled(false);
        this.usuario = usuario;
        setLabelIP();
        crearCliente();

    }

    //Constructor de un cliente
    public VElegirColor(String ipServer, String usuario) {
        initComponents();
        initPropio();

        this.setBounds(this.getX(), this.getY(), this.getWidth(), this.getHeight() - 40);
        this.jB_agregarJugador.setVisible(false);
        this.jB_iniciarPartida.setVisible(false);

        this.usuario = usuario;
        this.ipServer = ipServer;
        this.jL_IPServidor.setText("IP Servidor: " + this.ipServer);

        crearCliente();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bG_colores = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jRB_verde = new javax.swing.JRadioButton();
        jB_aceptar = new javax.swing.JButton();
        jRB_negro = new javax.swing.JRadioButton();
        jRB_rojo = new javax.swing.JRadioButton();
        jRB_azul = new javax.swing.JRadioButton();
        jRB_magenta = new javax.swing.JRadioButton();
        jRB_amarillo = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jB_iniciarPartida = new javax.swing.JButton();
        jB_agregarJugador = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jL_IPServidor = new javax.swing.JLabel();
        jL_nombrePartida = new javax.swing.JLabel();
        jL_tipoPartida = new javax.swing.JLabel();
        jL_tiempoTurno = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TEG CT - Elegir color");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Selección de color"));
        jPanel1.setLayout(null);

        jRB_verde.setBackground(new java.awt.Color(51, 255, 51));
        bG_colores.add(jRB_verde);
        jRB_verde.setName("Verde"); // NOI18N
        jRB_verde.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eventoRadio(evt);
            }
        });
        jPanel1.add(jRB_verde);
        jRB_verde.setBounds(35, 175, 180, 21);

        jB_aceptar.setText("Aceptar");
        jB_aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jB_aceptarActionPerformed(evt);
            }
        });
        jPanel1.add(jB_aceptar);
        jB_aceptar.setBounds(70, 200, 71, 23);

        jRB_negro.setBackground(new java.awt.Color(0, 0, 0));
        bG_colores.add(jRB_negro);
        jRB_negro.setForeground(new java.awt.Color(204, 204, 204));
        jRB_negro.setName("Negro"); // NOI18N
        jRB_negro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eventoRadio(evt);
            }
        });
        jPanel1.add(jRB_negro);
        jRB_negro.setBounds(35, 115, 180, 21);

        jRB_rojo.setBackground(new java.awt.Color(255, 0, 0));
        bG_colores.add(jRB_rojo);
        jRB_rojo.setForeground(new java.awt.Color(204, 204, 204));
        jRB_rojo.setName("Rojo"); // NOI18N
        jRB_rojo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eventoRadio(evt);
            }
        });
        jPanel1.add(jRB_rojo);
        jRB_rojo.setBounds(35, 145, 180, 21);

        jRB_azul.setBackground(new java.awt.Color(0, 0, 204));
        bG_colores.add(jRB_azul);
        jRB_azul.setForeground(new java.awt.Color(204, 204, 204));
        jRB_azul.setName("Azul"); // NOI18N
        jRB_azul.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eventoRadio(evt);
            }
        });
        jPanel1.add(jRB_azul);
        jRB_azul.setBounds(35, 55, 180, 21);

        jRB_magenta.setBackground(new java.awt.Color(102, 0, 102));
        bG_colores.add(jRB_magenta);
        jRB_magenta.setForeground(new java.awt.Color(204, 204, 204));
        jRB_magenta.setToolTipText("");
        jRB_magenta.setName("Magenta"); // NOI18N
        jRB_magenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eventoRadio(evt);
            }
        });
        jPanel1.add(jRB_magenta);
        jRB_magenta.setBounds(35, 85, 180, 21);

        jRB_amarillo.setBackground(new java.awt.Color(255, 255, 0));
        bG_colores.add(jRB_amarillo);
        jRB_amarillo.setName("Amarillo"); // NOI18N
        jRB_amarillo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eventoRadio(evt);
            }
        });
        jPanel1.add(jRB_amarillo);
        jRB_amarillo.setBounds(35, 25, 180, 21);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Verde.png"))); // NOI18N
        jPanel1.add(jLabel1);
        jLabel1.setBounds(10, 170, 30, 30);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Amarillo.png"))); // NOI18N
        jPanel1.add(jLabel2);
        jLabel2.setBounds(10, 20, 30, 30);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Azul.png"))); // NOI18N
        jPanel1.add(jLabel3);
        jLabel3.setBounds(10, 50, 30, 30);

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Magenta.png"))); // NOI18N
        jPanel1.add(jLabel4);
        jLabel4.setBounds(10, 80, 30, 30);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Negro.png"))); // NOI18N
        jPanel1.add(jLabel5);
        jLabel5.setBounds(10, 110, 30, 30);

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Rojo.png"))); // NOI18N
        jPanel1.add(jLabel6);
        jLabel6.setBounds(10, 140, 30, 30);

        jB_iniciarPartida.setText("Iniciar Partida");
        jB_iniciarPartida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jB_iniciarPartidaActionPerformed(evt);
            }
        });

        jB_agregarJugador.setText("Agregar jugador virtual");
        jB_agregarJugador.setEnabled(false);
        jB_agregarJugador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jB_agregarJugadorActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de la partida"));

        jL_IPServidor.setText("IP Servidor:");

        jL_tipoPartida.setText("jLabel7");

        jL_tiempoTurno.setText("jLabel7");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jL_IPServidor)
                    .addComponent(jL_nombrePartida, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                    .addComponent(jL_tipoPartida, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                    .addComponent(jL_tiempoTurno, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jL_IPServidor)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jL_nombrePartida, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jL_tipoPartida)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jL_tiempoTurno)
                .addContainerGap(129, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addComponent(jB_iniciarPartida, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
                .addComponent(jB_agregarJugador)
                .addGap(49, 49, 49))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jB_iniciarPartida)
                    .addComponent(jB_agregarJugador))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jB_aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_aceptarActionPerformed
    this.jB_agregarJugador.setEnabled(true);
    for (int i = 0; i < arrayJRB.size(); i++) {
        arrayJRB.get(i).setEnabled(false);
        if (arrayJRB.get(i).isSelected()) {
            cli.avisarSeleccionColor(arrayJRB.get(i).getName(), usuario);
            arrayJRB.get(i).setText("" + usuario);
            this.jB_aceptar.setEnabled(false);
        }
    }
    actualizarContador();
}//GEN-LAST:event_jB_aceptarActionPerformed

private void jB_iniciarPartidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_iniciarPartidaActionPerformed
    cli.avisarInicioPartida();
}//GEN-LAST:event_jB_iniciarPartidaActionPerformed

private void eventoRadio(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eventoRadio
    if (!this.jB_aceptar.isEnabled()) {
        this.jB_aceptar.setEnabled(true);
    }
}//GEN-LAST:event_eventoRadio

private void jB_agregarJugadorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_agregarJugadorActionPerformed
    ClienteVirtual cliV = new ClienteVirtual(this.ipServer, new ElegirColor(),this.tipoMision);
    cliV.start();
}//GEN-LAST:event_jB_agregarJugadorActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bG_colores;
    private javax.swing.JButton jB_aceptar;
    private javax.swing.JButton jB_agregarJugador;
    private javax.swing.JButton jB_iniciarPartida;
    private javax.swing.JLabel jL_IPServidor;
    private javax.swing.JLabel jL_nombrePartida;
    private javax.swing.JLabel jL_tiempoTurno;
    private javax.swing.JLabel jL_tipoPartida;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRB_amarillo;
    private javax.swing.JRadioButton jRB_azul;
    private javax.swing.JRadioButton jRB_magenta;
    private javax.swing.JRadioButton jRB_negro;
    private javax.swing.JRadioButton jRB_rojo;
    private javax.swing.JRadioButton jRB_verde;
    // End of variables declaration//GEN-END:variables

    private void setLabelIP() {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            this.ipServer = addr.getHostAddress();
            this.jL_IPServidor.setText("IP Servidor: " + this.ipServer);
        } catch (UnknownHostException e) {
        }
    }

    private void crearCliente() {
        cli = new Cliente(this.ipServer, this);
        cli.start();
    }

    public void seleccionColor(ArrayList<String> contenidoLineaEntrada) {
        String color = contenidoLineaEntrada.get(1);
        String usuario = contenidoLineaEntrada.get(2);
        for (int i = 0; i < arrayJRB.size(); i++) {
            if (arrayJRB.get(i).getName().compareTo(color) == 0) {
                arrayJRB.get(i).setText("" + usuario);
                arrayJRB.get(i).setEnabled(false);
            }
        }
        actualizarContador();
    }

    private void initPropio() {
        this.jB_aceptar.setEnabled(false);
        arrayJRB = new ArrayList();
        arrayJRB.add(jRB_amarillo);
        arrayJRB.add(jRB_azul);
        arrayJRB.add(jRB_magenta);
        arrayJRB.add(jRB_negro);
        arrayJRB.add(jRB_rojo);
        arrayJRB.add(jRB_verde);
    }

    //Al inicio
    public void seleccionColoresOcupados(ArrayList<String> contenidoLineaEntrada) {
        int cantidadUsuarios = Integer.parseInt(contenidoLineaEntrada.get(1));
        int contColor = 2;
        int contNombre = 3;
        for (int i = 0; i < cantidadUsuarios; i++) {

            for (int j = 0; j < arrayJRB.size(); j++) {
                if (arrayJRB.get(j).getName().compareTo(contenidoLineaEntrada.get(contColor)) == 0) {
                    arrayJRB.get(j).setText("" + contenidoLineaEntrada.get(contNombre));
                    arrayJRB.get(j).setEnabled(false);
                }
            }

            contColor += 2;
            contNombre += 2;
        }
    }

    public void setNombrePartida(String nombrePartida) {
        this.jL_nombrePartida.setText("Nombre de la partida: " + nombrePartida);
    }

    private void actualizarContador() {
        this.contElegidos++;
        if (this.contElegidos >= 2 && this.jB_iniciarPartida.isVisible()) {
            this.jB_iniciarPartida.setEnabled(true);
        }
        if (contElegidos > 5) {
            this.jB_agregarJugador.setEnabled(false);
        }
    }

    public void iniciarPartida(ArrayList<Jugador> jugadores, int[] paises, int jugadorComienzaRonda, int misionPropia, int[] tarjetas) {
        this.dispose();
        VPrincipal vp = new VPrincipal(cli, jugadores, paises, jugadorComienzaRonda, misionPropia, tarjetas, this.tiempoTurno, this.tipoMision);
        vp.setVisible(true);
        vp.setLocationRelativeTo(null);
    }

    public void avisarError() {
        JOptionPane.showOptionDialog(
                this,
                "No se ha encontrado el servidor o está ocupado.",
                "Error",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.ERROR_MESSAGE,
                null,
                null,
                "aceptar");

        VUnirse vu = new VUnirse(usuario);
        vu.setLocationRelativeTo(null);
        vu.setVisible(true);
        this.dispose();
    }

    public void setTiempoTurno(int tiempoTurno) {
        this.tiempoTurno = tiempoTurno;
        this.jL_tiempoTurno.setText("Tiempo turno: " + tiempoTurno);

    }

    public void setTipoMision(int tipoMis) {
        this.tipoMision = tipoMis;
        if (tipoMis == 0) {
            this.jL_tipoPartida.setText("Tipo Partida:  Misiones secundarias");
        } else if (tipoMis == 1) {
            this.jL_tipoPartida.setText("Tipo Partida:  Misiones simples");
        } else if (tipoMis == 2) {
            this.jL_tipoPartida.setText("Tipo Partida:  Conquista total");
        }

    }
}